package com.ruoyi.stock.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.api.event.EventListener;
import com.ruoyi.api.event.EventType;
import com.ruoyi.api.event.OrderExecutionEvent;
import com.ruoyi.stock.domain.StockInventory;
import com.ruoyi.stock.service.IStockInventoryService;
import com.ruoyi.stock.service.IStockInventoryLogService;
import com.ruoyi.stock.service.IStockAlertService;
import com.ruoyi.common.utils.ShiroUtils;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 销售订单执行事件监听器 - 用于减少库存数量
 */
@Component(value = "stockSalesOrderListener")
public class SalesOrderExecutionListener implements EventListener<OrderExecutionEvent> {

    private static final Logger logger = LoggerFactory.getLogger(SalesOrderExecutionListener.class);

    @Autowired
    private IStockInventoryService stockInventoryService;
    
    @Autowired
    private IStockInventoryLogService stockInventoryLogService;
    
    @Autowired
    private IStockAlertService stockAlertService;
    
    @Autowired
    private com.ruoyi.api.event.EventCenter eventCenter;
    
    @PostConstruct
    public void init() {
        // 注册监听器
        eventCenter.registerListener(this);
        logger.info("Registered Stock SalesOrderExecutionListener");
    }

    @Override
    public void onEvent(OrderExecutionEvent event) {
        if (event.getEventType() != EventType.SALES_ORDER_EXECUTED) {
            return;
        }
        
        logger.info("Processing sales order execution event for stock update, order ID: {}", event.getOrderId());
        
        try {
            // 从事件中直接获取数据，不再需要查询销售订单
            Long orderId = event.getOrderId();
            Long productId = event.getProductId();
            String productName = event.getProductName();
            Integer quantity = event.getQuantity();
            String orderCode = event.getOrderCode();
            
            if (productId == null || quantity == null || quantity <= 0) {
                logger.error("Invalid product ID or quantity in sales order event: {}", orderId);
                return;
            }
            
            // 查询该商品的库存记录
            StockInventory inventory = new StockInventory();
            inventory.setProductId(productId);
            inventory = stockInventoryService.selectStockInventoryList(inventory).stream()
                    .findFirst().orElse(null);
            
            if (inventory == null) {
                logger.error("No inventory record found for product ID: {} when processing sales order", productId);
                return;
            }
            
            // 检查库存是否足够
            if (inventory.getCurrentQuantity() < quantity) {
                logger.error("Insufficient stock for product: {}, required: {}, available: {}", 
                        productName, quantity, inventory.getCurrentQuantity());
                return;
            }
            
            // 记录原库存数量
            Long beforeQuantity = inventory.getCurrentQuantity();
            
            // 更新现有库存记录 - 减少库存数量
            logger.info("Updating inventory for product: {}, current quantity: {}, deducting: {}", 
                    productName, inventory.getCurrentQuantity(), quantity);
            
            // 减少库存数量
            long newQuantity = inventory.getCurrentQuantity() - quantity;
            inventory.setCurrentQuantity(newQuantity);
            
            // 更新库存
            stockInventoryService.updateStockInventory(inventory);
            logger.info("Updated inventory for product: {}, new quantity: {}", productName, newQuantity);
            
            // 记录库存变动日志
            String loginName = "system";
            try {
                loginName = ShiroUtils.getLoginName();
            } catch (Exception e) {
                // 忽略异常，使用默认值
            }
            
            // 记录库存变动日志
            stockInventoryLogService.recordInventoryChange(
                productId,
                productName,
                beforeQuantity,
                newQuantity,
                "2", // 2-出库
                "2", // 2-销售单
                orderId,
                inventory.getWarehouseCode(),
                loginName,
                "销售订单出库：" + orderCode
            );
            
            logger.info("Recorded inventory change log for product: {}", productName);
            
            // 检查是否需要库存预警
            if (stockAlertService.checkLowStockAlert(inventory)) {
                logger.warn("Low stock alert for product: {}, current: {}, lower limit: {}", 
                        productName, newQuantity, inventory.getLowerLimit());
                // 发送库存预警通知
                stockAlertService.sendLowStockAlert(inventory);
            }
            
        } catch (Exception e) {
            logger.error("Error updating inventory for sales order: {}", event.getOrderId(), e);
        }
    }

    @Override
    public EventType getSupportedEventType() {
        return EventType.SALES_ORDER_EXECUTED;
    }
    
    @Override
    public Class<OrderExecutionEvent> getSupportedEventClass() {
        return OrderExecutionEvent.class;
    }
} 